﻿using KnifeZ.Byeol.Models;
using KnifeZ.Byeol.Services;
using KnifeZ.Unity.EasyService;
using KnifeZ.Unity.Helper;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Web;

namespace KnifeZ.Byeol.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private string _title = "Prism Application";
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        private ObservableCollection<ByeolTask> taskList;
        public ObservableCollection<ByeolTask> TaskList
        {
            get { return taskList; }
            set { SetProperty(ref taskList, value); }
        }

        private int currentTaskIndex;
        /// <summary>
        /// 当前任务执行序号
        /// </summary>
        public int CurrentTaskIndex
        {
            get { return currentTaskIndex; }
            set { SetProperty(ref currentTaskIndex, value); }
        }
        private int totalExecuteTaskCount;
        /// <summary>
        /// 本轮执行任务数
        /// </summary>
        public int TotalExecuteTaskCount
        {
            get { return totalExecuteTaskCount; }
            set { SetProperty(ref totalExecuteTaskCount, value); }
        }

        private bool isFinished;
        public bool IsFinished
        {
            get { return isFinished; }
            set { SetProperty(ref isFinished, value); }
        }
        private string executeInfo;
        public string ExecuteInfo
        {
            get { return executeInfo; }
            set { SetProperty(ref executeInfo, value); }
        }

        public DelegateCommand ExecuteTasksCommmand { get; set; }

        //调度器
        IScheduler scheduler;
        //调度器工厂
        ISchedulerFactory factory;
        public void ExecuteTask()
        {
            IsFinished = false;
            #region Quartz.Net任务调度 --打开软件时启动调度器
            //1、创建一个调度器
            factory = new StdSchedulerFactory();
            scheduler =factory.GetScheduler().Result;
            scheduler.Start();
            foreach (var item in TaskList.Where(x => x.IsInterrupt == false))
            {
                //2、创建一个任务
                IJobDetail job = JobBuilder.Create<TimingJob>().WithIdentity("job" + item.ID, item.TaskGroupName).SetJobData(new JobDataMap() {
                    {"itemID", item.ID}
                }).Build();
                //3、创建一个触发器
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("trigger" + item.ID, item.TaskGroupName)
                    .WithCronSchedule(item.CronLambda)
                    .StartAt(item.CreateTime)
                    .Build();

                //4、将任务与触发器添加到调度器中
                scheduler.ScheduleJob(job, trigger);
            }
            //5、开始执行
            scheduler.Start();
            #endregion

            BackgroundWorker worker = new BackgroundWorker
            {
                WorkerSupportsCancellation = true,
                WorkerReportsProgress = true
            };
            worker.DoWork += (o, ea) =>
            {
                ExecuteInfo = "任务执行中[" + CurrentTaskIndex + "/" + TotalExecuteTaskCount + "]";
                while (!IsFinished)
                {
                    var date = DateTime.Now;
                    TotalExecuteTaskCount = TaskList.Where(x => x.IsInterrupt == false).Count();
                    CurrentTaskIndex = TaskList.Where(x => x.NextExecuteTime < date && x.IsInterrupt == false).Count();

                    ExecuteInfo = "任务执行中[" + CurrentTaskIndex + "/" + TotalExecuteTaskCount + "]";
                    for (int i = 0; i < 6; i++)
                    {
                        ExecuteInfo += ".";
                        Thread.Sleep(300);
                    }
                }
            };
            worker.RunWorkerAsync();
        }

        public DelegateCommand CancelTaskCommand { get; set; }
        public void CancelTask()
        {
            IsFinished = true;
            ExecuteInfo = "任务已中止";
            if (scheduler != null)
            {
                scheduler.Shutdown(true);
            }
        }
        public void RefreshTaskList(string message = "")
        {
            this.TaskList = new ObservableCollection<ByeolTask>();
            using DataContext db = new DataContext(AppSettings.DefaultConnectString);
            this.TaskList.AddRange(db.Set<ByeolTask>().AsNoTracking().ToList());
        }
        public MainWindowViewModel()
        {
            RefreshTaskList();
            ExecuteTasksCommmand = new DelegateCommand(new System.Action(ExecuteTask));
            CancelTaskCommand = new DelegateCommand(new Action(CancelTask));
            //订阅事件-刷新列表
            EventAggregatorRepository
                .GetInstance()
                .eventAggregator
                .GetEvent<PrismEventHandler<string>>()
                .Subscribe(RefreshTaskList, ThreadOption.UIThread, true);
        }
    }
}
